<template>
	<view class="box" @click="hideView">
		<view class="cu-chat">
			<view v-for="(item,index) in mgsList" :key='index' >
				<view :id='"id"+index' class="cu-item self" v-if='item.type===1'>
					<view class="main">
						<view v-if="item.msgType === 2" class="content shadow">
							{{item.text}}
						</view>
            <view v-if="item.msgType === 1" class="content shadow">
              <image @click="handleShowImage(item.text)" mode="aspectFit" :src="item.text"></image>
            </view>
					</view>
					<view class="cu-avatar radius" style="background-image:url('../../static/image/icon_me_selected.png');"></view>
					<view class="date">{{item.time}}</view>
				</view>
				<view :id='"id"+index' v-else class="cu-item">
					<view class="cu-avatar radius" style="background-image:url(../../static/image/icon_head_portrait_me.png);"></view>
					<view class="main">
						<view v-if="item.msgType === 2" class="content shadow">
              {{item.text}}
						</view>
            <view v-if="item.msgType === 1" class="content shadow">
              <image @click="handleShowImage(item.text)" mode="aspectFit" :src="item.text"></image>
            </view>
					</view>
					<view class="date">{{item.time}}</view>
				</view>
			</view>
		</view>
		<view class="cu-bar foot input" :style="[{bottom:InputBottom+'px'}]">
			<input class="solid-bottom" v-model="text" :adjust-position="false" :focus="false" maxlength="300" cursor-spacing="10"></input>
			<view class="action">
				<text @click.stop="showView" class="cuIcon-add text-grey"></text>
			</view>
			<button @click="handleSendMsg" class="cu-btn bg-green shadow">发送</button>
		</view>
    <view @click.stop="returnView" class="tools-box" :style="[{height:InputBottom+'px'}]">
      <view class="grid col-4 grid-square flex-sub">
        <view class="solids" >
          <text @click="ChooseImage" class='cuIcon-cameraadd'></text>
        </view>
      </view>
    </view>
	</view>
</template>
<script>
	import {PATH} from "@/utils";

  export default {
		data() {
			return {
				InputBottom: 0,
				websocke:null,
				text:'',
        imgUrl:'',
				mgsList:[],
				flag:false,
        view:true
			};
		},
		created() {
			this.websocke = uni.connectSocket({
			    url: "ws://www.jackysuen.top/joyletter/webSocketServer?userId="+6, //仅为示例，并非真实接口地址。
			    success:(res)=>{

          }
			});
			uni.onSocketMessage( (res)=> {
				if(!this.flag){
					this.flag = true
					this.changeMsgData(JSON.parse(res.data))
				}else{
					this.changeMsgData(res.data)
				}
			  // console.log('收到服务器内容：' + res.data);

			});
			uni.onSocketClose(function (res) {
			  console.log('WebSocket 已关闭！');
			});
			uni.onKeyboardHeightChange(res => {
			  console.log(res.height)
			  this.InputBottom = res.height
			})
		},
		onUnload() {
			if(this.websocke){
				this.websocke.close()
			}
		},
		methods: {
      handleShowImage(res){
        uni.previewImage({
          urls:[res]
        })
      },
      ChooseImage() {
        uni.chooseImage({
          count: 1, //默认9
          sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
          sourceType: ['album'], //从相册选择
          success: ({tempFilePaths}) => {
            uni.uploadFile({
              url: PATH+'/onload/uploadImg', //仅为示例，非真实的接口地址
              filePath: tempFilePaths[0],
              name: 'file',
              success: (uploadFileRes) => {
                const imgUrl = JSON.parse(uploadFileRes.data).imgurl
                if( this.websocke ){
                  this.mgsList.push({
                    type:1,
                    text: imgUrl,
                    msgType:1,
                    time:this.timestampToTime(new Date().getTime())
                  })
                  setTimeout(()=>{
                    uni.pageScrollTo({
                      scrollTop:100000,
                      duration: 200
                    });
                  },500)
                  this.websocke.send({
                    data:imgUrl ,
                    success:()=>{
                      this.text = ''
                      this.imgUrl = ''
                    }
                  })
                }
              }
            });
          }
        });
      },
      showView(){
        this.InputBottom = 200
      },
      returnView(){},
			// 处理数据
			changeMsgData(res){
				if( Object.prototype.toString.call(res) === '[object Array]' ){
					var list = []
          console.log(res)
          console.log("=================")
          for (var i = 0; i < res.length; i++) {
            // console.log(res[i])
            if (res[i].userMessage) {
              list.push({
                text: res[i].userMessage,
                type: 1,
                msgType: res[i].userMessage.indexOf('http://47.93.25.131/upload/') === 0 ? 1 : 2,  // 1：图片 2：文字
                time: res[i].sendTime
              })
            }
            if (res[i].sysReply) { // 系统
              list.push({
                text: res[i].sysReply,
                type: 2,
                msgType: res[i].sysReply.indexOf('http://47.93.25.131/upload/') === 0 ? 1 : 2, // 1：图片 2：文字
                time: res[i].replyTime
              })
            }
          }
					this.mgsList = this.mgsList.concat(list)
				}else{

					this.mgsList.push({
						text: JSON.parse(res)[0].sysReply,
						type:2,
            msgType: JSON.parse(res)[0].sysReply.indexOf('http://47.93.25.131/upload/') === 0 ? 1 : 2,  // 1：图片 2：文字
						time:this.timestampToTime(new Date().getTime())
					})
				}
				const query = uni.createSelectorQuery().in(this);
				setTimeout(()=>{
					uni.pageScrollTo({
					    scrollTop:100000,
					    duration: 200
					});
				},500)
				/* setTimeout(e=>{
					let id = '#id' + String(this.mgsList.length-1)
					console.log(id)
					query.select(id).boundingClientRect(data => {
						console.log(data.top)

					}).exec();
				},500) */
			},
			timestampToTime(timestamp) {
			      const date = new Date(timestamp)// 时间戳为10位需*1000，时间戳为13位的话不需乘1000
			      const Y = date.getFullYear() + '-'
			      const M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
			      const D = date.getDate() + ' '
			      const h = date.getHours() + ':'
			      const m = date.getMinutes() + ':'
			      const s = date.getSeconds()
			      return Y + M + D + h + m + s
			    },
			handleSendMsg(){

				if( this.websocke ){
					this.mgsList.push({
						type:1,
						text: this.text,
            msgType:2,
						time:this.timestampToTime(new Date().getTime())
					})
					setTimeout(()=>{
						uni.pageScrollTo({
						    scrollTop:100000,
						    duration: 200
						});
					},500)
					this.websocke.send({
						data:this.imgUrl || this.text,
						success:()=>{
							this.text = ''
              this.imgUrl = ''
            }
					})
				}
			},
			InputFocus(e) {
				this.InputBottom = e.detail.height
			},
      hideView(){
        this.InputBottom = 0
      },
			InputBlur(e) {
				this.InputBottom = 0
			}
		}
	}
</script>

<style >
.cu-avatar{
	background-color: unset;
}
page{
  padding-bottom: 100upx;
}
.tools-box{
  overflow: hidden;
  box-sizing: border-box;
  z-index: 999;
  padding: 40upx;
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  background: #fff;
}
.content image{
  width: 250upx;
  height: 250upx;
}
</style>
